﻿Imports System.Globalization
Imports mDataStore
Imports System.Data

Partial Class Lecture_View
    Inherits System.Web.UI.Page
    Public msg As String = ""
    Public importdone As String = ""
    Private _listItems As List(Of ListItemData)
    Private _ExelFileName As String
    Private fn As String
    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Dim Action As String = ""

            If Not IsNothing(Request.Form("action")) Then
                Action = Request.Form("action")
            End If

            If Action = "import" Then
                VerifyRegister()
            ElseIf Action = "remove" Then
                If Not IsNothing(Request.Form("hiddenID")) Then
                    mRemoveLecturer(Request.Form("hiddenID"))
                End If
            End If
        Catch ex As Exception
            Response.Write(ex.Message)
            'MsgBox(ex.StackTrace)
        End Try
    End Sub
    Private Function VerifyRegister() As Boolean

        If IsNothing(readFile.PostedFile) Then
            msg = "<table class=""error_table"">" & _
                           "<th><span>File Error</span></th><th><span>The input file is invalid!</span></th>" & _
                       "</table>"
            Return False
        Else
            'MsgBox(Server.MapPath("Files"))
            fn = System.IO.Path.GetFileName(readFile.PostedFile.FileName)
            If fn.Contains(".xls") Or fn.Contains(".xlsx") Then
                fn = Now.ToString("ddMMyyyyHHmmss") & IIf(fn.Contains(".xlsx"), ".xlsx", ".xls")
                Dim SaveLocation As String = Server.MapPath("Files") & "\" & fn
                readFile.PostedFile.SaveAs(SaveLocation)
                If getDataToImport() = True Then
                    Try
                        Dim fiFile As New System.IO.FileInfo(Server.MapPath("Files") & "\" & fn)
                        fiFile.Delete()
                    Catch Exc As System.Exception
                        Response.Write("Error: " & Exc.Message)
                    End Try
                    Return True
                Else
                    'Response.Write("false")
                    Return False
                End If

                Return True
            Else
                msg = "<table class=""error_table"">" & _
                           "<th><span>File Error</span></th><th><span>The input file is invalid!</span></th>" & _
                       "</table>"
                Return False
            End If
        End If
    End Function

    Public Property ExelFileName() As String
        Get
            Return _ExelFileName
        End Get
        Set(ByVal value As String)
            _ExelFileName = value
        End Set
    End Property
    Public Property ListItems() As List(Of ListItemData)
        Get
            Return _listItems
        End Get
        Set(ByVal value As List(Of ListItemData))
            _listItems = value
        End Set
    End Property
    Private Function getDataToImport() As Boolean

        'Dim MyConvert As New Viet2Uni()
        Try
            'MyConvert.Source = Viet2Uni.Codes.VNI
            'MyConvert.Destination = Viet2Uni.Codes.UTF8
            ListItems = Utilities.readFileExcel(Server.MapPath("Files") & "\" & fn, fn)
            Dim dtGroup As New DataTable
            dtGroup.Columns.Add(New DataColumn("timeslot_group"))
            dtGroup.Columns.Add(New DataColumn("timeslot_to"))
            dtGroup.Columns.Add(New DataColumn("timeslot_from"))
            dtGroup.Columns.Add(New DataColumn("timeslot_day"))
            Dim rowNo As Integer = 1
            For Each li As ListItemData In ListItems
                Dim errorMsg As String = ""
                Dim count As Integer = 0
                Dim s0 As String = ""
                Dim s1 As String = ""
                Dim s2 As String = ""
                Dim s3 As String = ""
                Dim s4 As String = ""
                Dim s5 As String = ""
                Dim s6 As String = ""
                Dim s7 As String = ""
                'Dim s8 As String = ""
                'Dim s9 As String = ""
                'Dim s10 As String = ""
                'Dim s11 As String = ""
                'Dim s12 As String = ""
                'Dim s13 As String = ""
                'Dim s14 As String = ""
                'Dim s15 As String = ""
                'Dim s16 As String = ""
                'Dim s17 As String = ""
                'Dim s18 As String = ""
                'Dim s19 As String = ""
                'Dim s20 As String = ""
                'Dim s21 As String = ""
                'Dim s22 As String = ""
                'Dim s23 As String = ""
                'Dim s24 As String = ""
                For Each i As ItemData In li.ListItem
                    i.ConditionValidate = ""
                    If count = 0 Then
                        s0 = i.Value    'Lecturer Number
                        errorMsg += check_Empty(s0.Trim, "Lecturer Number")
                    End If

                    If count = 1 Then
                        s1 = i.Value   'Lecturer Name
                        errorMsg += check_Empty(s1.Trim, "Lecturer Name")
                    End If
                    If count = 2 Then
                        s2 = i.Value   'Lecturer Area of Expertise
                        errorMsg += check_Empty(s2.Trim, "Lecturer Area of Expertise")
                    End If
                    If count = 3 Then
                        s3 = i.Value   'Number of Session
                        errorMsg += check_Number(s3.Trim, "Number of Session")
                    End If
                    If count = 4 Then
                        s4 = i.Value   'First Choice
                        errorMsg += check_Empty(s4.Trim, "First Choice")
                        errorMsg += check_Group(dtGroup, s4.Trim)
                    End If

                    If count = 5 Then
                        s5 = i.Value    'Second Choice
                        errorMsg += check_Group(dtGroup, s5.Trim)
                    End If
                    If count = 6 Then
                        s6 = i.Value    'Third Choice
                        errorMsg += check_Group(dtGroup, s6.Trim)
                    End If
                    If count = 7 Then
                        s7 = i.Value    'Additional Note
                    End If
                    count = count + 1
                    If count = 8 Then
                        Try
                            If errorMsg <> "" Then
                                msg += "<tr><td>" & rowNo & "</td><td> " & errorMsg & "</td></tr>"
                            Else
                                If Request.Form("action").ToString = "import" Then
                                    Try
                                        importdone += "<tr><td>" & rowNo & "</td>" & ImportRecordsToDatabase(s0, s1, s2, s3, s4, s5, s6, s7) & "</tr>" ', s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19, s20, s21, s22) & "</tr>"
                                    Catch ex As System.Exception
                                        msg += "<tr><td>" & rowNo & "</td><td>" & ex.Message & " " & ex.StackTrace & "</td></tr>" 'when you done debuging CHANGE THIS TO UNKNOWN ERROR
                                    End Try
                                Else
                                    importdone += "<tr><td>" & rowNo & "</td><td>Data is checked.</td></tr>"
                                End If
                            End If
                            'Response.Write(s0.ToString & "|" & s1 & "|" & s2 & "|" & s3 & "|" & s4.ToString & "|" & s5 & "|" & s6 & "|" & s7 & "|" & s8 & "|" & s9 & "|" & s10 & "|" & s11 & "|" & s12 & "|" & s13 & "|" & s14 & "|" & s15 & "|" & s16 & "|" & s17 & "|" & s18 & "|" & s19 & "|" & s20 & "<br/>")

                        Catch exc As System.Exception
                            Response.Write(exc.ToString)
                        End Try
                        count = 0
                    End If
                Next
                rowNo += 1
            Next
            If msg.Trim <> "" Then
                msg = "<table class=""error_table"">" & _
                            "<th><span>Error Row</span></th><th><span>Error Details</span></th>" & _
                            msg & _
                        "</table>"
            End If
            If importdone.Trim <> "" Then
                If Request.Form("action") = "import" Then


                    importdone = "<table class=""import_done"">" & _
                                "<tr><th><span>Imported Row</span></th><th>Lecturer Number</th><th>Lecturer Name</th><th>Area of Expertise</th><th>Number of Session</th><th>First Choice</th><th>Second Choice</th><th>Third Choice</th><th>Note</th></tr>" & _
                                importdone & _
                            "</table>"
                    'import group table
                    mImportGroup(dtGroup)
                Else
                    importdone = "<table class=""import_done"">" & _
                                "<tr><th><span>Checked Row</span></th><th>Message</th></tr>" & _
                                importdone & _
                            "</table>"
                End If
            End If
            Return True
        Catch ex As System.Exception
            Response.Write(ex.ToString)
            Return False
        End Try
    End Function
    Private Function check_Group(ByRef dt As DataTable, ByVal sTarget As String) As String
        Dim sError As String = ""
        If sTarget.Trim <> "" Then
            Dim sTemp() As String = sTarget.Split("/")
            If sTemp.Length >= 5 Then

                dt.DefaultView.RowFilter = "timeslot_group ='" & sTemp(enChoices.enGroup) & "'"
                If dt.DefaultView.Count = 0 Then
                    'validate day, time
                    sError &= check_Date(sTemp(enChoices.enDate), "Group Date", "Date")
                    sError &= check_Date(sTemp(enChoices.enFrom), "Group From Time", "Time")
                    sError &= check_Date(sTemp(enChoices.enTo), "Group To Time", "Time")
                    If sError <> "" Then
                        Return sError
                    Else
                        Dim trTemp As DataRow = dt.NewRow
                        trTemp.Item("timeslot_group") = sTemp(enChoices.enGroup)
                        trTemp.Item("timeslot_to") = sTemp(enChoices.enTo)
                        trTemp.Item("timeslot_from") = sTemp(enChoices.enFrom)
                        trTemp.Item("timeslot_day") = sTemp(enChoices.enDate)
                        dt.Rows.Add(trTemp)
                    End If
                End If
            Else
                Return ("The " & sTarget & " has wrong format.")
            End If
        End If
        Return ""
    End Function
    Private Function check_Number(ByVal target As String, ByVal name As String) As String

        If IsNumeric(target.Replace(" ", "")) Then
            Return ""
        Else
            Return name & " should contains number. "
        End If

    End Function
    Private Function check_Empty(ByVal target As String, ByVal name As String) As String
        If target.Trim <> "" Then
            Return ""
        Else
            Return "Missing " & name & ". "
        End If
    End Function
    Private Function check_Date(ByVal target As String, ByVal name As String, ByVal sOption As String) As String
        If target.Trim <> "" Then
            If sOption = "Date" Then
                Try
                    ' For GB Culture Pass en-GB
                    ' coz date string is in dd/MM/yyyy
                    Dim Culture As IFormatProvider = New CultureInfo("en-GB", True)
                    DateTime.Parse(target.Trim, Culture, DateTimeStyles.NoCurrentDateDefault).ToString("dd/MMM/yyyy")
                    Return ""
                Catch ex As System.Exception
                    Return name & " should have dd/MMM/yyyy format. "
                End Try
            Else
                Try
                    ' For GB Culture Pass en-GB
                    ' coz date string is in dd/MM/yyyy
                    Dim Culture As IFormatProvider = New CultureInfo("en-GB", True)
                    DateTime.Parse(target.Trim, Culture, DateTimeStyles.NoCurrentDateDefault).ToString("HH:mm")
                    Return ""
                Catch ex As System.Exception
                    Return name & " should have HH:mm format. "
                End Try
            End If

        Else
            Return "Mising " & name & ". "
        End If
    End Function

    Private Enum enChoices
        enDate = 0
        enFrom = 1
        enTo = 2
        enGroup = 3
        enNote = 4
    End Enum
    Private Sub mImportGroup(ByVal dt As DataTable)
        For Each dr As DataRow In dt.Rows
            'MsgBox("xxx" & dr("timeslot_to") & "xxx")
            mAddGroup(dr("timeslot_group"), CDate(dr("timeslot_to").ToString.Trim), CDate(dr("timeslot_from").ToString.Trim), dr("timeslot_day").ToString.Trim)
        Next
    End Sub
    Private Function ImportRecordsToDatabase(ByVal ltrNumber As String, _
                                        ByVal ltrName As String, _
                                        ByVal AreaOfExp As String, _
                                        ByVal NoSession As Integer, _
                                        ByVal FirstChoice As String, _
                                        ByVal SecondChoice As String, _
                                        ByVal ThirdChoice As String, _
                                        ByVal AdditionNote As String) As String
        Dim done As StringBuilder = New StringBuilder("")

        Dim sG2, sG3 As String
        If String.IsNullOrEmpty(SecondChoice.Trim) Then
            sG2 = " "
        Else
            sG2 = SecondChoice.Split("/")(enChoices.enGroup)
        End If
        If String.IsNullOrEmpty(SecondChoice.Trim) Then
            sG3 = " "
        Else
            sG3 = SecondChoice.Split("/")(enChoices.enGroup)
        End If
        mAddLecturer(ltrNumber, ltrName, NoSession, FirstChoice.Split("/")(enChoices.enGroup), sG2, sG3, AdditionNote)


        Dim sEXPs() As String = AreaOfExp.Split(",")
        For Each sExp As String In sEXPs
            mAddExp(sExp, ltrNumber)
        Next

        done.AppendFormat("<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td><td>{7}</td>", _
                            ltrNumber, ltrName, AreaOfExp, NoSession, FirstChoice, SecondChoice, ThirdChoice, AdditionNote)

        Return done.ToString

    End Function
End Class
